const StorageKey = "giteeParameterKey";
//gitee 接口 配置 参数
const giteeParameter = {};
/**
 * 
  access_token: "",
  owner: "",
  repo: "",
  path: "",
  sha: ""
  url:""
 */
// 获取Gitee的参数
function getGiteeParameter(callback) {
  getChromeStorage(StorageKey, function (data) {
    giteeParameter.access_token = data.access_token;
    giteeParameter.url = data.url;
    giteeParameter.owner = data.owner;
    giteeParameter.repo = data.repo;
    giteeParameter.path = data.path;
    giteeParameter.sha = data.sha;
    callback()
  });
}

$(function () {
  getChromeStorageSync(StorageKey).then(data => {
    if (data) {
      $("#access_token").val(data.access_token);
      $("#giteeUrl").val(data.url);
    }
  }).catch(err => {
    alert(err)
  })
  //设置gitee参数
  $("#seting").click(function () {
    let giteeUrl = $("#giteeUrl").val();
    if (giteeUrl.length == 0) {
      alert("请配置giteeUrl");
      return;
    }
    if (giteeUrl.indexOf("https://gitee.com/") != 0) {
      alert("giteeUrl格式不正确");
      return;
    }
    let giteeUrlAryy = giteeUrl.replace("https://gitee.com/", "").replace(".git", '').split("/");
    let owner = giteeUrlAryy[0];
    let repo = giteeUrlAryy[1];
    let path = "bookmark.json";
    let access_token = $("#access_token").val();

    if (access_token.length == 0) {
      alert("请配置access_token");
      return;
    }
    giteeParameter.url = giteeUrl;
    giteeParameter.access_token = access_token;
    giteeParameter.owner = owner;
    giteeParameter.repo = repo;
    giteeParameter.path = path;
    //判断gittee文件是否存在
    blame2(giteeParameter).then(data => {
      if (data.length == 0) {
        return createFile2(giteeParameter, "W10=", "newFile");
      } else {
        return new Promise((resolve, reject) => { resolve({ content: data }); })
      }
    }).then(data => {
      giteeParameter.sha = data.content.sha;
      return setChromeStorageSync(StorageKey, giteeParameter)
    }).then(msg => { alert(msg); }).catch(error => { alert(error); })
    /*
    blame(giteeParameter, function (data) {
      if (data.length == 0) {
        //不存在
        //W10=  => []
        createFile(giteeParameter, "W10=", "newFile", function (data) {
          if (data.content) {
            giteeParameter.sha = data.content.sha;
            setChromeStorage(StorageKey, giteeParameter)
            alert("创建成功");
          } else {
            alert("创建失败,请查看配置!");
          }
        })
      } else {
        //存在 
        giteeParameter.sha = data.sha;
        setChromeStorage(StorageKey, giteeParameter)
        alert("设置配置完成!");
      }
    });
    */
    /*
    if (confirm("Are you sure you want to set this as your default access token?")) {
    }
    */
  });
  //提交
  $("#submit").click(function () {
    if (giteeParameter) {
      getChromeStorageSync(StorageKey).then(data => {
        if (data) {
          giteeParameter.url = data.url;
          giteeParameter.access_token = data.access_token;
          giteeParameter.owner = data.owner;
          giteeParameter.repo = data.repo;
          giteeParameter.path = data.path;
          giteeParameter.sha = data.sha;
        } else {
          alert("请先设置配置!");
          return
        }
      }).then(a => {
        return gtreesha2(giteeParameter)
      }).then(data => {
        if (data.sha) {
          giteeParameter.sha = data.sha;
        }
        return chromeBookmarksGetTree()
      }).then(data => {
        let bookmarksJson = JSON.stringify(data);
        let base64str = base64Encode(bookmarksJson);
        let message = formatDate(new Date());
        return PutFile(giteeParameter, message, base64str)
      }).then(data => {
        giteeParameter.sha = data.content.sha;
        if (data.content) {
          var opt = {
            type: "basic",
            title: "上传成功",
            message: "上传成功",
            iconUrl: "img/icons/icon64.png"
          };
          createChromeNotifications("myNotification" + formatDate(new Date()), opt, function () { });
        } else {
          var opt = {
            type: "basic",
            title: "上传失败",
            message: "上传失败",
            iconUrl: "img/icons/icon64.png"
          };
          createChromeNotifications("myNotification" + formatDate(new Date()), opt, function () { });
        }
        //console.log(data)
      }).catch(err => { })
    } else {
      alert("请先设置配置!");
    }
    return
    getGiteeParameter(function () {
      getTreeChromeBookmarks(function (bookmarkTreeNodes) {
        let bookmarksJson = JSON.stringify(bookmarkTreeNodes);
        // 将JSON字符串转换为Base64编码
        let base64Bookmarks = base64Encode(bookmarksJson);
        gtreesha(giteeParameter.access_token, giteeParameter.owner, giteeParameter.repo, giteeParameter.path, '', function (sha) {
          let message = formatDate(new Date());
          getreeput(giteeParameter.access_token, giteeParameter.owner, giteeParameter.repo, giteeParameter.path, sha, message, base64Bookmarks, function (response) {
            var opt = {
              type: "basic",
              title: "上传成功",
              message: "上传成功",
              iconUrl: "img/icons/icon64.png"
            };
            createChromeNotifications("myNotification", opt, function () { });
          }, function (xhr, status, error) {
            var opt = {
              type: "basic",
              title: "上传失败",
              message: "上传失败",
              iconUrl: "img/icons/icon64.png"
            };
            createChromeNotifications("myNotification", opt, function () { });
          })
        })
      });
    });
  });
  //拉取
  $("#pull").click(function () {
    let bookmarkTreeNodes = [];
    if (giteeParameter) {
      getChromeStorageSync(StorageKey).then(data => {
        if (data) {
          giteeParameter.url = data.url;
          giteeParameter.access_token = data.access_token;
          giteeParameter.owner = data.owner;
          giteeParameter.repo = data.repo;
          giteeParameter.path = data.path;
          giteeParameter.sha = data.sha;
        } else {
          alert("请先设置配置!");
          return
        }
      }).then(a => {
        return gtreesha2(giteeParameter)
      }).then(data => {
        if (data.sha) {
          giteeParameter.sha = data.sha;
        }
        let trees = base64Decode(data.content);
        console.log(trees);
        bookmarkTreeNodes = JSON.parse(trees);
        return chromeBookmarksGetTree();
      }).then(data => {
        let localbookmarkTreeNodes = data;
        if (localbookmarkTreeNodes.length > 0 && localbookmarkTreeNodes[0].children.length > 0) {
          localbookmarkTreeNodes = localbookmarkTreeNodes[0].children[0].children
          for (let i = 0; i < localbookmarkTreeNodes.length; i++) {
            removeTreeChromebookmarks(localbookmarkTreeNodes[i].id, function () { })
          }
        }
      }).then(text => {
        if (bookmarkTreeNodes.length > 0 && bookmarkTreeNodes[0].children.length > 0) {
          bookmarkTreeNodes = bookmarkTreeNodes[0].children[0].children
          createChromeBookmarksTree(bookmarkTreeNodes, 0)
        }
      }).then(a => {
        var opt = {
          type: "basic",
          title: "同步成功",
          message: "同步成功",
          iconUrl: "img/icons/icon64.png"
        };
        createChromeNotifications("SyncSuccessful"+formatDate(new Date()), opt, function () { });
      }).catch(err => { })
    } else {
      alert("请先设置配置!");
    }
  });
  /*
  $("#pull").click(function () {
    getGiteeParameter(function () {
      gtreesha(giteeParameter.access_token, giteeParameter.owner, giteeParameter.repo, giteeParameter.path, '', function (sha) {
        giteeBlob(giteeParameter.access_token, giteeParameter.owner, giteeParameter.repo, sha, function (data) {
          let trees = base64Decode(data.content);
          let bookmarkTreeNodes = JSON.parse(trees);
          getTreeChromeBookmarks(function (localbookmarkTreeNodes) {
            if (localbookmarkTreeNodes.length > 0 && localbookmarkTreeNodes[0].children.length > 0) {
              localbookmarkTreeNodes = localbookmarkTreeNodes[0].children[0].children
              for (let i = 0; i < localbookmarkTreeNodes.length; i++) {
                removeTreeChromebookmarks(localbookmarkTreeNodes[i].id, function () { })
              }
            }
            if (bookmarkTreeNodes.length > 0 && bookmarkTreeNodes[0].children.length > 0) {
              bookmarkTreeNodes = bookmarkTreeNodes[0].children[0].children
              createChromeBookmarksTree(bookmarkTreeNodes, 0)
              var opt = {
                type: "basic",
                title: "同步成功",
                message: "同步成功",
                iconUrl: "img/icons/icon64.png"
              };
              createChromeNotifications("SyncSuccessful", opt, function () { });
            }
          })
        })
      });
    });
  })
  */
});